package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.*;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.robert.vesta.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class RupeeGoService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RupeeGoService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private CeRepaymentLinkDao ceRepaymentLinkDao;


    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("rupeego", this);
        BaseJobHandler.merchantAndServiceMap.put("therupee", this);
        BaseJobHandler.merchantAndServiceMap.put("springloan", this);
    }


    public boolean autoLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isAutoLoginOpen()) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String url = merchant.getApiDomain() + "/admin/login";
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            Map<String, String> headers = getHeaders(agentAccount);
            headers.remove("accessToken");
            headers.remove("appCode");
            JSONObject params = new JSONObject();
            params.put("account", agentAccount.getAccount());
            params.put("verifyCode", agentAccount.getPassword());
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            if (StringUtils.isNotEmpty(JsonIterator.deserialize(result).get("data").toString())) {
                LOGGER.error("== 自动登录成功==，data:{}", JsonIterator.deserialize(result).get("data").toString());
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("basicParams", "{'appClient': 'web'}");
                requestHeader.put("appCode", "1");
                requestHeader.put("accessToken", JsonIterator.deserialize(result).get("data").get("accessToken").toString());
                requestHeader.put("Content-Type", "application/json");
                if (merchant.getMerchantCode().equals("rupeego")) {
                    requestHeader.put("productCategory", "rupeeGoV1All");
                } else if (merchant.getMerchantCode().equals("therupee")) {
                    requestHeader.put("productCategory", "theRupeeV1All");
                }
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return true;
            } else {
                LOGGER.info("== 自动登录失败 ==");
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
            }
        } else {
            LOGGER.info("== 未开启自动登录 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return false;
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            boolean isLogin = autoLogin(agentAccount);
            if (!isLogin) {
                return false;
            }
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/admin/productCategory/list";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);
        if (StringUtils.isEmpty(JsonIterator.deserialize(result).get("data").toString())) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return autoLogin(agentAccount);
        }

        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== RupeeGoService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    public void completedOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/collection/v2/distributeOrderGet/list?currentPage=1&pageSize=500";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);


        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        JSONObject params = new JSONObject();
        params.put("collectionType", "0");
        params.put("endDate", DateUtil.getDate("yyyy-MM-dd"));
        params.put("startDate", DateUtil.getDate("yyyy-MM-dd"));
        params.put("sort", "2");
        params.put("sortType", "repaymentDate");
        params.put("workTaskStatus", "completed");
        String result = HttpUtil.postPageBody(url, headers, params.toString());
        Any resultJson = JsonIterator.deserialize(result);

        if (StringUtils.isEmpty(resultJson.get("data").toString())) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
//        String url = merchant.getApiDomain() + "/collection/v2/distributeOrderGet/list?currentPage=1&pageSize=2";
        //测试获取少量数据
        String url = merchant.getApiDomain() + "/collection/v2/distributeOrderGet/list?currentPage=1&pageSize=500";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);


        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        JSONObject params = new JSONObject();
        params.put("collectionType", "0");
        params.put("endDate", DateUtil.getDate("yyyy-MM-dd"));
        params.put("startDate", DateUtil.getDate("yyyy-MM-dd"));
        params.put("sort", "2");
        params.put("sortType", "repaymentDate");
        params.put("workTaskStatus", "doing");
        String result = HttpUtil.postPageBody(url, headers, params.toString());
        Any resultJson = JsonIterator.deserialize(result);

        if (StringUtils.isEmpty(resultJson.get("data").toString())) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        if (resultJson.get("data") == null) {
            LOGGER.info("== 请求接口数据为空 ==，account:{}", agentAccount.getAccount());
            return;
        }
        List<Any> items = resultJson.get("data").get("itemList").asList();


        if (CollectionUtils.isEmpty(items)) {
            LOGGER.info("== 请求接口数据为空  item 为空==，account:{}", agentAccount.getAccount());
//            activeOrders.forEach(ceOrdersEntity->{
//                if (ceOrdersEntity.getStatus().equals(OrderStatusEnum.active.getStatus())) {
//                    ceOrdersEntity.setStatus(OrderStatusEnum.removed.getStatus());
//                    ceOrdersEntity.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
//                    ordersDao.updateByPrimaryKey(ceOrdersEntity);
//                }
//            });
            return;
        }

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //如果为空则全部选择插入，这个其实就是初始化数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("==当天没有数活跃数据 开始插入新数据 ==，size:{}", items.size());
            items.forEach(item -> {
                try {
                    String collectionNo = IdUtils.genId() + "";
                    CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                            .setAgentCode(agentAccount.getAgentCode())
                            .setMerchantCode(agentAccount.getMerchantCode())
                            .setOrderNo(item.get("tradeNo").toString())
                            .setOrderInfo(item.toString())
                            .setStatus(OrderStatusEnum.active.getStatus())
                            .setCreateDt(new Date())
                            .setCollectionNo(collectionNo);
                    ordersDao.insert(ceOrdersEntity);
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });
        } else {
            //更新数据
            LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());
            Map<String, CeOrdersEntity> activeOrdersMap = new HashMap<>();
            Set<String> newOrdersSet = new HashSet<>();
            activeOrders.forEach(o -> {
                activeOrdersMap.put(o.getOrderNo(), o);
            });
            items.forEach(item -> {
                String loanId = item.get("tradeNo").toString();
                newOrdersSet.add(loanId);
            });

            //如果更新之后发现有新的订单了，则继续插入
            items.forEach(item -> {
                try {
                    String tradeNo = item.get("tradeNo").toString();

                    if (!activeOrdersMap.containsKey(tradeNo)) {
                        LOGGER.info("==更新的时候发现有新的订单==,account:{},tradeNo:{}", agentAccount.getAccount(), tradeNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(item.get("tradeNo").toString())
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    } else {
                        LOGGER.info("==更新的时候订单已存在==,account:{},tradeNo:{}", agentAccount.getAccount(), tradeNo);
                        CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNo(tradeNo);
                        String collectionNo = todayOneByOrderNo.getCollectionNo();
                        String remainMoney = JsonIterator.deserialize(item.toString()).get("collectionOrderDetailVoList").asList().get(0).get("noRepayAmount").toString();
                        updateRemainMoney(collectionNo, remainMoney);
                    }

                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });

            //如果跟新之后发现数据比原来的少了，则需要更新订单状态
            activeOrdersMap.keySet().forEach(activeOrderNo -> {
                try {
                    if (!newOrdersSet.contains(activeOrderNo)) {
                        LOGGER.info("== 更新的时候发现有订单消失 目前认为是订单状态发生了改变 ==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo);
                        CeOrdersEntity ceOrdersEntity = activeOrdersMap.get(activeOrderNo);
                        if (ceOrdersEntity.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            ceOrdersEntity.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(ceOrdersEntity);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.info("==更新的时候发现有订单 异常==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo, e);
                }
            });
        }

        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();
                if (!hasDetailData) {
                    String orderInfo = order.getOrderInfo();
                    String tradeNo = JsonIterator.deserialize(orderInfo).get("tradeNo").toString();
                    CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "baseInfo", order.getOrderNo());
                    if (baseInfoDetail == null) {
                        String baseInfoUrl = merchant.getApiDomain() + "/user/" + tradeNo + "/base/info";
                        String baseInfo = HttpUtil.postPage(baseInfoUrl, params, headers);
                        infoMap.put("baseInfo", JsonIterator.deserialize(baseInfo).get("data").get("list").toString());
                        LOGGER.info("== 获取成功 baseInfo==");
                    } else {
                        baseInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(baseInfoDetail);
                    }


                    CeOrdersDetailEntity contactInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "contactInfo", order.getOrderNo());
                    if (contactInfoDetail == null) {
                        String contactInfoUrl = merchant.getApiDomain() + "/user/" + tradeNo + "/contact/info";
                        String contactInfo = HttpUtil.postPage(contactInfoUrl, params, headers);
                        LOGGER.info("== 获取成功 contactInfo==");
                        infoMap.put("contactInfo", JsonIterator.deserialize(contactInfo).get("data").get("contacts").toString());
                    } else {
                        contactInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactInfoDetail);
                    }

                    CeOrdersDetailEntity workInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "workInfo", order.getOrderNo());
                    if (workInfoDetail == null) {
                        String workInfoUrl = merchant.getApiDomain() + "/user/" + tradeNo + "/work/info";
                        String workInfo = HttpUtil.postPage(workInfoUrl, params, headers);
                        infoMap.put("workInfo", JsonIterator.deserialize(workInfo).get("data").get("list").toString());
                        LOGGER.info("== 获取成功 workInfo==");
                    } else {
                        workInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(workInfoDetail);
                    }


                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        String addressBookUrl = merchant.getApiDomain() + "/user/" + tradeNo + "/audit/contactCall/info";
                        String addressBook = HttpUtil.postPage(addressBookUrl, params, headers);
                        List<Any> contactList;
                        try {
                            contactList = JsonIterator.deserialize(addressBook).get("data").get("list").asList();
                            if (CollectionUtils.isNotEmpty(contactList)) {
                                JSONArray contacts = new JSONArray();
                                for (Any vo : contactList) {
                                    JSONObject j1 = new JSONObject();
                                    j1.put("name", vo.get("name").toString());
                                    if (!vo.get("phone").toString().equals("")) {
                                        j1.put("phone", vo.get("phone").toString());
                                        contacts.add(j1);
                                    }
                                }
                                JSONObject jsonData = new JSONObject();
                                jsonData.put("contacts", contacts);

                                String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                infoMap.put("contactUrl", contactUrl);
                            }
                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                        LOGGER.info("== 获取成功 contactUrl==");
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }

                    CeOrdersDetailEntity fileListDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "fileList", order.getOrderNo());
                    if (fileListDetail == null) {
                        String fileListUrl = merchant.getApiDomain() + "/user/" + tradeNo + "/faceRecognition/info";
                        String fileList = HttpUtil.getPage(fileListUrl, params, headers);
                        LOGGER.info("== 获取成功 fileList==");
                        infoMap.put("fileList", JsonIterator.deserialize(fileList).get("data").toString());

                        Any imagesDetail = JsonIterator.deserialize(fileList).get("data");
                        ImagesVo imagesVo = new ImagesVo();
                        if (!imagesDetail.get("aadhaarFrontImage").toString().equals("")) {
                            imagesVo.setAadhaarFrontImage(imagesDetail.get("aadhaarFrontImage").asList().get(0).get("imgUrl").toString());
                        }
                        if (!imagesDetail.get("aadhaarBackImage").toString().equals("")) {
                            imagesVo.setAadhaarBackImage(imagesDetail.get("aadhaarBackImage").asList().get(0).get("imgUrl").toString());
                        }
                        if (!imagesDetail.get("aadhaarHandheldImage").toString().equals("")) {
                            imagesVo.setSelfieImage(imagesDetail.get("aadhaarHandheldImage").asList().get(0).get("imgUrl").toString());
                        }
                        infoMap.put("images", JsonStream.serialize(imagesVo));
                    } else {
                        fileListDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(fileListDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("appName").toString();
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");
                Any collectionOrderDetailVoList = orderDetail.get("collectionOrderDetailVoList").asList().get(0);
                String borrowCapital = collectionOrderDetailVoList.get("realCapital").toString();
                String overdueDays = collectionOrderDetailVoList.get("overdueDays").toString();
                String lateFee = collectionOrderDetailVoList.get("lateFee").toString();
                String overdueRatio = "0";
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                String paidAmount = new BigDecimal(collectionOrderDetailVoList.get("expireAmount").toString()).subtract(new BigDecimal(collectionOrderDetailVoList.get("noRepayAmount").toString())).toString();
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(1)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest(collectionOrderDetailVoList.get("interest").toString())
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee("0")
                        .setLateServiceFee("0")
                        .setReceivedCapital("0")
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(DateUtil.getConverseDay(collectionOrderDetailVoList.get("repaymentDate").toString(), 7))
                        .setRepaymentDate(DateUtil.getDate(DateUtil.getDate(collectionOrderDetailVoList.get("repaymentDate").toString(), "yyyy-MM-dd"), "yyyy-MM-dd"))
                        .setRemainMoney(collectionOrderDetailVoList.get("noRepayAmount").toString())
                        .setTotalMoney(collectionOrderDetailVoList.get("expireAmount").toString());

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                CeOrdersDetailEntity fileListInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "fileList", order.getOrderNo());
                List<Any> personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo()).asList();
                Any fileListInfoJson = JsonIterator.deserialize(fileListInfo.getDetailInfo());

                String aadhaarNo = fileListInfoJson.get("kycCardId").toString();
                String pancardNo = "";
                String email = "";
                String age = "";
                String mobile = "";
                String name = "";
                String state = "";
                String gender = "";
                String address = "";
                String pinCode = "";
                String city = "";
                String birthDay = "";
                for (int i = 0; i < personalInfoJson.size(); i++) {
                    if (personalInfoJson.get(i).get("name").toString().equals("PAN")) {
                        pancardNo = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("Email")) {
                        email = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("Age")) {
                        age = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("Mobile")) {
                        mobile = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("Name")) {
                        name = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("State")) {
                        state = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("Gender")) {
                        gender = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("Address")) {
                        address = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("PinCode")) {
                        pinCode = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("City")) {
                        city = personalInfoJson.get(i).get("value").toString();
                    } else if (personalInfoJson.get(i).get("name").toString().equals("Date of Birth")) {
                        birthDay = personalInfoJson.get(i).get("value").toString();
                    }
                }

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() == 3) {
                    parentName = StringUtils.isEmpty(contactInfoJson.get(1).get("name").toString())?"no-data":contactInfoJson.get(1).get("name").toString();
                    parentPhone = contactInfoJson.get(1).get("mobile").toString();
                    friendName = StringUtils.isEmpty(contactInfoJson.get(2).get("name").toString())?"no-data":contactInfoJson.get(2).get("name").toString();
                    friendMobile = contactInfoJson.get(2).get("mobile").toString();
                } else if (contactInfoJson.size() == 2) {
                    parentName = StringUtils.isEmpty(contactInfoJson.get(0).get("name").toString())?"no-data":contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("mobile").toString();
                    friendName = StringUtils.isEmpty(contactInfoJson.get(1).get("name").toString())?"no-data":contactInfoJson.get(1).get("name").toString();
                    friendMobile = contactInfoJson.get(1).get("mobile").toString();
                }


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                Map<String, Any> stringAnyMap = JsonIterator.deserialize(iamges.getDetailInfo()).asMap();

                List<String> images = new ArrayList<>();
                stringAnyMap.values().forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(StringUtils.isEmpty(birthDay) ? DateUtil.getConverseDay(new Date().toString(), Integer.parseInt(age)) : birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(0)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(0)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex("female".equals(gender) ? 0 : 1)
                        .setContactUrl(contactUrlEntity.getDetailInfo())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        JSONObject params = new JSONObject();
        params.put("collectionType", "0");
        params.put("endDate", DateUtil.getDate("yyyy-MM-dd"));
        params.put("startDate", DateUtil.getDate("yyyy-MM-dd"));
        params.put("sort", "2");
        params.put("sortType", "repaymentDate");
        params.put("workTaskStatus", "completed");

        waitingPaidCheckOrders.forEach(order -> {
            String url = merchant.getApiDomain() + "/collection/v2/distributeOrderGet/list?currentPage=1&pageSize=500";
            LOGGER.info("== 开始请求已还款订单列表 ==,url:{}", url);
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            Any resultJson = JsonIterator.deserialize(result);
            if (resultJson.get("data").toString().equals("")) {
                LOGGER.info("== 已还款订单列表异常 ==");
                return;
            }
            List<Any> anies = resultJson.get("data").get("itemList").asList();
            for (Any any : anies) {
                if (any.get("tradeNo").toString().equals(order.getOrderNo())) {
                    LOGGER.info("== 已还款订单列表存在订单 ==,tradeNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                    order.setStatus(OrderStatusEnum.paid_update.getStatus());
                    ordersDao.updateByPrimaryKey(order);
                    return;
                }
            }
            LOGGER.info("== 已还款订单列表不存在订单 ==,tradeNo:{}", order.getOrderNo());
            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                Any collectionOrderDetailVoList = JsonIterator.deserialize(order.getOrderInfo()).get("collectionOrderDetailVoList").asList().get(0);
                String paidAmount = new BigDecimal(collectionOrderDetailVoList.get("expireAmount").toString()).subtract(new BigDecimal(collectionOrderDetailVoList.get("noRepayAmount").toString())).toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                Any collectionOrderDetailVoList = JsonIterator.deserialize(order.getOrderInfo()).get("collectionOrderDetailVoList").asList().get(0);
//                String paidAmount = new BigDecimal(collectionOrderDetailVoList.get("expireAmount").toString()).subtract(new BigDecimal(collectionOrderDetailVoList.get("noRepayAmount").toString())).toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        RupeeGoCollectionTagEnum currentTag = RupeeGoCollectionTagEnum.RNR_V2;

        for (RupeeGoCollectionTagEnum e : RupeeGoCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(ceCommentPushLogEntity.getOriginNo());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        try {
            Map<String, String> headers = getHeaders(account);
            JSONObject params = new JSONObject();
            params.put("collectionNo", orderInfo.get("collectionNo").toString());
            params.put("content", currentTag.getDesc());
            params.put("followId", orderInfo.get("followId").toString());
            params.put("followUp", orderInfo.get("followUp").toString());
            params.put("mobile", orderInfo.get("mobile").toString());
            params.put("name", orderInfo.get("name").toString());
            params.put("tradeNo", orderInfo.get("tradeNo").toString());
            params.put("type", String.valueOf(ceCommentPushLogEntity.getTargetType()));
            params.put("userCode", orderInfo.get("userCode").toString());

            String result = HttpUtil.postPageBody(ceMerchantEntity.getApiDomain() + "/collection/v2/comment/add", headers, params.toString());
            LOGGER.info("== 开始同步催记到甲方 ==,res:{}", result);

            if ("0".equals(JsonIterator.deserialize(result).get("code").toString())) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==");
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo,boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());

        String link = "";
        Map<String, String> headers = getHeaders(accountEntity);
        HashMap<String, String> params = Maps.newHashMap();
        String url = ceMerchantEntity.getApiDomain() + "/liquidation/v2/" + ceOrdersEntity.getOrderNo() + "/repayment/info?needLink=true&paymentDt=" + DateUtil.getDate("yyyy-MM-dd");
        LOGGER.info("== 获取rupeeGo还款链接 ==,url:{}", url);
        String result = HttpUtil.postPage(url, params, headers);
        LOGGER.info("== 获取rupeeGo还款链接 ==,url:{},res:{}", url, result);
        Any resultJson = JsonIterator.deserialize(result);
        if (!"".equals(resultJson.get("data").toString())) {
            link = resultJson.get("data").get("repaymentInfo").get("repayLink").toString();
            LOGGER.info("== 获取还款链接 ==,link:{}", link);
        }else{
            LOGGER.error("== 获取还款链接失败 ==,account:{},loanId:{}", ceOrdersEntity.getAgentCode(),ceOrdersEntity.getOrderNo());
        }
        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());


        String renewLink = "";
        Map<String, String> renewHeaders = getHeaders(accountEntity);
        HashMap<String, String> renewParams = Maps.newHashMap();
        String renewUrl = ceMerchantEntity.getApiDomain() + "/liquidation/v2/" + ceOrdersEntity.getOrderNo() + "/extension/repayment/info";
        LOGGER.info("== 获取rupeeGo展期还款链接 ==,renewUrl:{}", renewUrl);
        renewParams.put("needLink", "true");
        renewParams.put("paymentDt", DateUtil.getDate("yyyy-MM-dd"));
        String renewResult = HttpUtil.postPage(renewUrl, renewParams, renewHeaders);
        LOGGER.info("== 获取rupeeGo展期还款链接结果 ==,renewResult:{}", renewResult);
        Any renewResultJson = JsonIterator.deserialize(renewResult);
        if (!"".equals(renewResultJson.get("data").toString())) {
            renewLink = renewResultJson.get("data").get("repaymentInfo").get("repayLink").toString();
            LOGGER.info("== 获取展期还款链接 ==,renewLink:{}", renewLink);
        }
        return renewLink;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }


    @Override
    public String queryPaymentOrderResult(String orderNo,String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }

    public static void main(String[] args) {

        String renewLink = "";
        Map<String, String> renewHeaders = Maps.newHashMap();
        renewHeaders.put("basicParams", "{'appClient': 'web'}");
        renewHeaders.put("appCode", "1");
        renewHeaders.put("accessToken", "00752efa87c0c8f6a56a8b48c8f49826");
        renewHeaders.put("Content-Type", "application/json");
        HashMap<String, String> renewParams = Maps.newHashMap();
        String renewUrl = "http://admin-api.fortunestack.in//liquidation/v2/238437384696373730TD/repayment/info";
        LOGGER.info("== 获取rupeeGo展期还款链接 ==,renewUrl:{}", renewUrl);
        renewParams.put("needLink", "true");
        renewParams.put("paymentDt", DateUtil.getDate("yyyy-MM-dd"));
        String renewResult = HttpUtil.postPage(renewUrl, renewParams, renewHeaders);
        LOGGER.info("== 获取rupeeGo展期还款链接结果 ==,renewResult:{}", renewResult);
        Any renewResultJson = JsonIterator.deserialize(renewResult);
        if (!"".equals(renewResultJson.get("data").toString())) {
            renewLink = renewResultJson.get("data").get("repaymentInfo").get("repayLink").toString();
            LOGGER.info("== 获取展期还款链接 ==,renewLink:{}", renewLink);
        }
    }

    private static String getBirthDayByAge(Integer age) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.YEAR, -age);
        Date y = c.getTime();
        return format.format(y);
    }
}
